
tactile.logger.setLevel(tactile.logger.level.error);
var page = tactile.page;

var ajaxloader = new function() {
    var data = {};

    this.init = function () {
        var ajaxProductLoader = new tactile.AjaxLoader();
        ajaxProductLoader.onstart.subscribe(function(response){
            console.log("onstart: ", response);
        });
        ajaxProductLoader.load({
            url: 'http://cloud.netbiscuits.net/1030549/DevStylebook/content/data/products.json',
            method: 'get',
            params: ''
        });
        ajaxProductLoader.onsuccess.subscribe(function(response){
            console.log("onsucces: ", response);
            data = eval('(' + ajaxProductLoader.getResponseText() + ')');            
        });
        ajaxProductLoader.onerror.subscribe(function(){
            console.log("onerror: ",arguments);
        });
        
        
    };
    this.getData = function() {
        return data;
    };
};



var HomeTablet = function () {
    
    var fbInitialize = false;
    var splashLoaded = false;
    var fashionspreadSelectedIndex = 0;
    var fashionLikes = new Array();
    var mnStyleInitialize = false;
    var mnStyleLandscape = new Array();
    var mnStylePortrait = new Array();
    var mnFashionGridInitialize = new Array();
    
    //fashion grid tap button
    var fashiongridControl = {
        view: tactile.page.getComponent("vw-fashiongrid"),
        beforeShowHandler: function(e) {
            if (!mnFashionGridInitialize[fashionspreadSelectedIndex]) {
                
                //load the remote content
                var content = "/content/fashiongrid.xml";
                var containername= "vw-fashiongrid";                
                
                var contentloader = new tactile.ContentLoader();
                contentloader.load({
                    url : content
                });        
                contentloader.onsuccess.subscribe(function(e) { 
                    var container = tactile.View.cast(page.getComponent(containername));
                    if (container != 'undefined' && container != null) {
                        var contentToLoad = tactile.View.cast(contentloader.getComponent(containername + "-remote"));
                        container.append(contentToLoad);
                        
                        var btnOpenItemConfigs = document.querySelectorAll(".btnViewVonfigProduct");
                        for (var i=0; i<btnOpenItemConfigs.length; i++) {
                            (function(i) {
                                btnOpenItemConfigs[i].id = "viewConfig" + (i+1);
                                tactile.EventManager.addListener(btnOpenItemConfigs[i].id, "tap", (function (e) {
                                    
                                    for (var j=0; j<btnOpenItemConfigs.length; j++) {
                                        var toHide = page.getComponent("vw-config-item-"  + (j+1));
                                        if (toHide.isVisible()) {
                                            toHide.hide({
                                                slideto : tactile.Enum.Direction.south,
                                                slidefrom : tactile.Enum.Direction.north
                                            });
                                        }
                                    }
                                    
                                    console.log("Show Config for Item No. " + (i+1));
                                    var vwconfig = page.getComponent("vw-config-item-"  + (i+1));
                                    vwconfig.show({
                                        slideto : tactile.Enum.Direction.north,
                                        slidefrom : tactile.Enum.Direction.south
                                    });
                                }).bind(btnOpenItemConfigs[i]));				
                            })(i);                                    
                        }    
                        
                        var btnCloseItemConfigs = document.querySelectorAll(".btncloseconfigproduct");
                        for (var i=0; i<btnOpenItemConfigs.length; i++) {
                            (function(i) {
                                btnCloseItemConfigs[i].id = "closeConfig" + (i+1);
                                tactile.EventManager.addListener(btnCloseItemConfigs[i].id, "tap", (function (e) {
                                    console.log("Close Config for Item No. " + (i+1));
                                    var vwconfig = page.getComponent("vw-config-item-"  + (i+1));
                                    vwconfig.hide({
                                        slideto : tactile.Enum.Direction.south,
                                        slidefrom : tactile.Enum.Direction.north
                                    });
                                }).bind(btnCloseItemConfigs[i]));	                                
                            })(i);                                    
                        }    
                        
                        
                        mnFashionGridInitialize[fashionspreadSelectedIndex] = true;
                    }
                });
                contentloader.onerror.subscribe( function(e) {
                    console.log(e);
                });
            }
        },
        afterShowHandler: function(e) {
            hideSocialButton(e);
            hideOpenFashionGridButton(e);
            showCloseFashionGridButton(e);
            fashiongridControl.view.isActive = true;
        },
        beforeHideHandler: function(e) {
            hideCloseFashionGridButton(e);
            var vwItemConfigs = document.querySelectorAll(".vw-config-item");
            for (var i=0; i<vwItemConfigs.length; i++) {
                (function(i) {
                    var vwconfig = page.getComponent("vw-config-item-"  + (i+1));
                    if (vwconfig.isVisible()) {
                        vwconfig.hide({
                            slideto : tactile.Enum.Direction.south,
                            slidefrom : tactile.Enum.Direction.north
                        });    
                    }
                })(i);                                    
            }               
        },
        afterHideHandler: function(e) {
            fashiongridControl.view.isActive = false;
        }
    }
    
    var menu_actions = {
        beforeShowHandler: function(e) {
            console.log("start menu beforeShowHandler");

            this.init();

            if (!(this.btn == null || this.btn == 'undefined')) {
                util.addClass(this.btn.elem, "selected");
            }
        
            if (fashiongridControl.view.isActive) {
                var toHide = tactile.View.cast(fashiongridControl.view);
                toHide.hide({
                    slideto : tactile.Enum.Direction.south,
                    slidefrom : tactile.Enum.Direction.north
                });     
            }
        
            console.log("end menu beforeShowHandler");
        },
        afterShowHandler: function(e) {
            console.log("start menu afterShowHandler");
            if (this.hasSocialButton) {
                showSocialButton(e);
            }
            
            if (this.hasToggleButton) {
                showOpenFashionGridButton(e);
            } 
            
            if (this.hasLikeButton) {
                showLikeButton(e);
            }
            
            this.view.isActive = true;

            tactile.foundation.LayoutManager.updateLayout();
            console.log("end menu afterShowHandler");
        },
        beforeHideHandler: function(e) {
            console.log("start menu beforeHideHandler");

            if (!(this.btn == null || this.btn == 'undefined')) {
                util.removeClass(this.btn.elem, "selected");
            }

            hideOpenFashionGridButton(e);
            hideCloseFashionGridButton(e);
            hideSocialButton(e);
            hideLikeButton(e);

            console.log("end menu beforeHideHandler");                
        },
        afterHideHandler: function(e) {
            console.log("start menu afterHideHandler");
            this.view.isActive = false;
            console.log("end menu afterHideHandler"); 
        } 
    }
    
    //menu buttons
    var menu_btns =  {
        mn_fashionspread : { 
            btn: tactile.page.getComponent("menu-fashionspread"), 
            view: tactile.page.getComponent("vw-fashionspread"),
            hasSocialButton: true,
            hasToggleButton: true,
            hasLikeButton: true,
            init: function(e) {
            //do nothing
            }
        },
        mn_mystyle : { 
            btn: tactile.page.getComponent("menu-mystyle"), 
            view: tactile.page.getComponent("vw-mystyle"),
            hasSocialButton: false,
            hasToggleButton: false,
            hasLikeButton: false,
            init: function(e) {
                //load the remote content
                var content = "/content/mystyle.xml";
                var containername= "vw-mystyle";
                
                if (!mnStyleInitialize) {
                    var contentloader = new tactile.ContentLoader();
                    contentloader.onsuccess.subscribe(function(e) { 
                        var container = tactile.View.cast(page.getComponent(containername));
                        if (container != 'undefined' && container != null) {
                            var contentToLoad = tactile.View.cast(contentloader.getComponent(containername+ "-remote"));

                            var fwmystylelandscape = page.getComponent("fw-mystyle-selected-list-landscape");
                            var iconslandscape= fwmystylelandscape.elem.querySelectorAll(".close");
                            for (var i=0; i<iconslandscape.length; i++) {
                                (function(i) {
                                    iconslandscape[i].id = "iconslandscape" + (i+1);
                                    tactile.EventManager.addListener(iconslandscape[i].id, "tap", (function (e) {
                                        console.log("Landscape Mode = Hide MyStyle Item No. " + (i+1));
                                    }).bind(iconslandscape[i]));				
                                })(i);                                    
                            }  

                            var mvmystyleportrait = tactile.MultiView.cast(page.getComponent("mv-mystyle-selected-list-portrait"));
                            tactile.EventManager.addListener("mv-mystyle-selected-list-portrait", "swipe", onswipeHandler.bind(mvmystyleportrait));                
                            var iconsportrait= mvmystyleportrait.elem.querySelectorAll(".close");
                            for (var j=0; j<iconsportrait.length; j++) {
                                (function(j) {
                                    iconsportrait[j].id = "iconsportrait" + (j+1);
                                    tactile.EventManager.addListener(iconsportrait[j].id, "tap", (function (e) {
                                        console.log("Portrait Mode - Hide MyStyle Item No. " + (j+1));
                                    }).bind(iconsportrait[j]));				
                                })(j);                                    
                            }	
                            
                            
                            var recommendedItems = document.querySelectorAll(".recommendeditem");
                            for (var k=0; k<recommendedItems.length; k++) {
                                (function(k) {
                                    tactile.EventManager.addListener(recommendedItems[k].id, "tap", (function (e) {
                                        console.log("Show Recommended Item No. " + (k+1));
                                        var popup = tactile.Layout.cast(page.getComponent("mystyle-like-overlay"));
                                        popup.show();
                                    }).bind(recommendedItems[k]));				
                                })(k); 
                            }

                            container.append(contentToLoad);
                            mnStyleInitialize = true;
                        }
                    });
                    contentloader.onerror.subscribe( function(e) {
                        console.log(e);
                    });                
                    contentloader.load({
                        url : content
                    }); 
                }
       
            }              
        },
        mn_shoppingbasket : { 
            btn: tactile.page.getComponent("menu-shoppingbasket"), 
            view: tactile.page.getComponent("vw-shoppingbasket"),
            hasSocialButton: false,
            hasToggleButton: false,
            hasLikeButton: false,
            init: function(e) {
            //load the remote content
            }              
           
        }
    }    
    
    var shareOnFacebookTapHandler = function() {
        console.log("facebook share");
        
        var obj = {
            method: 'feed',
            display: 'popup',
            link: 'http://cloud.netbiscuits.net/1030549/DevStylebook/',
            picture: encodeURI(location.href + 'images/fashionspread/landscape/prod' + fashionspreadSelectedIndex + '.jpg'),
            name: 'Stylebook',
            caption: 'Netbiscuits Tactile Demo',
            description: 'Welcome to Stylebook'
        };

        function callback(response) {
            if (response && response.post_id) {
                console.log("Facebook POST ID: " + response.post_id);
            }else {
                console.log("Post was not published.");
            }
        };

        if (!fbInitialize) {
            console.log("facebook initialize");
            FB.init({
                appId: "402321596483195", 
                channelUrl : "http://cloud.netbiscuits.net/1030549/DevStylebook/",
                status: true, 
                cookie: true,
                xfbml:false
            });
            fbInitialize=true;
        }
        FB.ui(obj, callback);     
    }
    
    var shareOnTwitterTapHandler = function() {
        console.log("twitter share");
        var twitterShareUrl = "http://www.twitter.com/share/?text=Stylebook&url=" + encodeURI("http://cloud.netbiscuits.net/1030549/DevStylebook/");
        window.open(twitterShareUrl);
    }
    
    var onswipeHandler = function(e) {
        var direction;
        
        direction = e.direction.toUpperCase();	
        if (direction == "LEFT") {		
            this.showNext({
                slideto: tactile.Enum.Direction.west, 
                slidefrom: tactile.Enum.Direction.east
            });
        } else if (direction == "RIGHT") {	
            this.showPrev({
                slideto: tactile.Enum.Direction.east,
                slidefrom: tactile.Enum.Direction.west
            });
        } 
        
        fashionspreadSelectedIndex = this.selectedIndex;
    }    
    
    var hideOpenFashionGridButton = function(e) {
        var openfashiongridbutton = tactile.Layout.cast(page.getComponent("open-fashiongrid-button-overlay"));
        openfashiongridbutton.hide();        
    }
    
    var hideCloseFashionGridButton= function(e) {
        var closefashiongridbutton = tactile.Layout.cast(page.getComponent("close-fashiongrid-button-overlay"));
        closefashiongridbutton.hide();
    }
    
    var showOpenFashionGridButton= function(e) {
        var openfashiongridbutton = tactile.Layout.cast(page.getComponent("open-fashiongrid-button-overlay"));
        openfashiongridbutton.show();             
    }
    
    var showCloseFashionGridButton= function(e) {
        var closefashiongridbutton = tactile.Layout.cast(page.getComponent("close-fashiongrid-button-overlay"));
        closefashiongridbutton.show();
    }
    
    var showSocialButton= function(e) {
        var socialbuttons = tactile.Layout.cast(page.getComponent("sidebar-overlay"));
        socialbuttons.show();
    }    
    
    var hideSocialButton= function(e) {
        var socialbuttons = tactile.Layout.cast(page.getComponent("sidebar-overlay"));
        socialbuttons.hide();
    }    
    
    var showLikeButton = function(e) {
        var likebutton = tactile.Layout.cast(page.getComponent("like-button"));
        likebutton.show();
    }
    
    var hideLikeButton = function(e) {
        var likebutton = tactile.Layout.cast(page.getComponent("like-button"));
        likebutton.hide();
    }

    var toggleLike = function(e) {
        var likebutton = page.getComponent("ilikebtn");
        util.toggleClass(likebutton.elem,"selected");
        
        if (tactile.Device.screen.isLandscape()) {
            var mvfashionspreadlandscape= page.getComponent("mv-fashionspread-landscape");
            if (fashionLikes[mvfashionspreadlandscape.selectedIndex]==null || fashionLikes[mvfashionspreadlandscape.selectedIndex]=='undefined'){
                fashionLikes[mvfashionspreadlandscape.selectedIndex] = true;
            }else {
                fashionLikes[mvfashionspreadlandscape.selectedIndex] = !fashionLikes[mvfashionspreadlandscape.selectedIndex];
            }
            if (!fashionLikes[mvfashionspreadportrait.selectedIndex]) {
                var mvmystyleportrait = tactile.MultiView.cast(page.getComponent("mv-mystyle-selected-list-portrait"));
                var viewToRemove = mvmystyleportrait.getViewByIndex(mvfashionspreadportrait.selectedIndex);
                mnStylePortrait.push(viewToRemove);
                mvmystyleportrait.remove(viewToRemove);
            }
        }else if (tactile.Device.screen.isPortrait()) {
            var mvfashionspreadportrait= page.getComponent("mv-fashionspread-portrait");
            if (fashionLikes[mvfashionspreadportrait.selectedIndex]==null || fashionLikes[mvfashionspreadportrait.selectedIndex]=='undefined'){
                fashionLikes[mvfashionspreadportrait.selectedIndex] = true;
            }else {
                fashionLikes[mvfashionspreadportrait.selectedIndex] = !fashionLikes[mvfashionspreadportrait.selectedIndex];
            }
            if (!fashionLikes[mvfashionspreadlandscape.selectedIndex]) {
                var fwmystylelandscape = page.getComponent("fw-mystyle-selected-list-landscape")
                var viewToRemove = fwmystylelandscape.getViewByIndex(mvfashionspreadlandscape.selectedIndex);
                mnStyleLandscape.push(viewToRemove);
                fwmystylelandscape.remove(viewToRemove);
            }
        }            
    }
    
    var registerListener = function() {
        //register swipe event for fashion spread
        var mvfashionspreadlandscape= page.getComponent("mv-fashionspread-landscape");
        tactile.EventManager.addListener("mv-fashionspread-landscape", "swipe", onswipeHandler.bind(mvfashionspreadlandscape));
        mvfashionspreadlandscape.onswitch.subscribe((function(e){
            var likebutton = page.getComponent("ilikebtn");
            if (fashionLikes[mvfashionspreadlandscape.selectedIndex]) {
                util.addClass(likebutton.elem,"selected");
            }else {
                util.removeClass(likebutton.elem,"selected");
            }
        }).bind(mvfashionspreadlandscape));
        
        var mvfashionspreadportrait= page.getComponent("mv-fashionspread-portrait");
        tactile.EventManager.addListener("mv-fashionspread-portrait", "swipe", onswipeHandler.bind(mvfashionspreadportrait));
        mvfashionspreadportrait.onswitch.subscribe((function(e){
            var likebutton = page.getComponent("ilikebtn");
            if (fashionLikes[mvfashionspreadportrait.selectedIndex]) {
                util.addClass(likebutton.elem,"selected");
            }else {
                util.removeClass(likebutton.elem,"selected");
            }
        }).bind(mvfashionspreadportrait));        
        
        //register onresize --> sync the landscape and portrait index
        var vwfashionspread = page.getComponent("vw-fashionspread");
        vwfashionspread.onresize.subscribe((function(e){
            if (tactile.Device.screen.isPortrait()) {
                if (mvfashionspreadportrait.isVisible()) {
                    mvfashionspreadportrait.showView(mvfashionspreadlandscape.selectedIndex);
                }
            }else {
                if (mvfashionspreadlandscape.isVisible()) {
                    mvfashionspreadlandscape.showView(mvfashionspreadportrait.selectedIndex);
                }
            }
        }).bind(vwfashionspread));

        //register tap event for twitter and facebook
        tactile.EventManager.addListener("fbshare","tap", shareOnFacebookTapHandler);
        tactile.EventManager.addListener("twitter","tap", shareOnTwitterTapHandler);        
        
        //fashiongrid action
        tactile.EventManager.addListener("btn-open-fashiongrid","tap", (function (e) {
            console.log("start - tap btn-open-fashiongrid");
            
            var toHide = menu_btns["mn_fashionspread"].view;
            toHide.hide();
            
            var toShow = tactile.View.cast(this.view);
            toShow.show({
                slideto : tactile.Enum.Direction.north,
                slidefrom : tactile.Enum.Direction.south
            });
            console.log("end - tap btn-open-fashiongrid");
        }).bind(fashiongridControl));
        tactile.EventManager.addListener("btn-close-fashiongrid","tap",(function (e) {
            console.log("start - tap btn-close-fashiongrid");
            var toHide = tactile.View.cast(this.view);
            toHide.hide({
                slideto : tactile.Enum.Direction.south,
                slidefrom : tactile.Enum.Direction.north
            });

            var toShow = menu_btns["mn_fashionspread"].view;
            toShow.show();
            
            console.log("end - tap btn-close-fashiongrid");
        }).bind(fashiongridControl));
        fashiongridControl.view.beforehide.subscribe(fashiongridControl.beforeHideHandler);
        fashiongridControl.view.afterhide.subscribe(fashiongridControl.afterHideHandler);
        fashiongridControl.view.beforeshow.subscribe(fashiongridControl.beforeShowHandler);
        fashiongridControl.view.aftershow.subscribe(fashiongridControl.afterShowHandler);        
        fashiongridControl.view.isActive= false;           
        
        //register tap even for menu
        for (var i in menu_btns) {
            menu_btns[i].view.beforehide.subscribe(menu_actions.beforeHideHandler.bind(menu_btns[i]));
            menu_btns[i].view.afterhide.subscribe(menu_actions.afterHideHandler.bind(menu_btns[i]));
            menu_btns[i].view.beforeshow.subscribe(menu_actions.beforeShowHandler.bind(menu_btns[i]));
            menu_btns[i].view.aftershow.subscribe(menu_actions.afterShowHandler.bind(menu_btns[i]));
            tactile.EventManager.addListener(menu_btns[i].btn.elem.id, "tap", (function (e) {
                var toHide, toShow = this.view;
                for (var j in menu_btns) {
                    if (menu_btns[j].view != this.view && menu_btns[j].view.isActive) {
                        toHide = menu_btns[j].view;
                    }
                }
                if (toHide==null || toHide=='undefined') {
                    if (fashiongridControl.view.isActive) {
                        toHide = fashiongridControl.view;
                        toHide.hide({
                            slideto : tactile.Enum.Direction.south,
                            slidefrom : tactile.Enum.Direction.north
                        });                    
                    }
                }else {
                    toHide.hide();
                }
                
                toShow.show();                
            }).bind(menu_btns[i]));
        }
        menu_btns["mn_fashionspread"].view.isActive=true;          
        
        tactile.EventManager.addListener("ilikebtn","tap", function(e) {
            toggleLike();
        });        
    }
    
    var displaySplashScreen = function(e) {
        
        if (!splashLoaded) {
            var content = "/content/splash.xml";
            var containername= "vw-splash-content";        
        
            var contentloader = new tactile.ContentLoader();
            contentloader.onsuccess.subscribe(function(e) { 
                var container = tactile.Layout.cast(page.getComponent(containername));
                if (container != 'undefined' && container != null) {
                    var contentToLoad = tactile.View.cast(contentloader.getComponent(containername+ "-remote"));
                    container.append(contentToLoad);
                    container.show();
                    splashLoaded = true;
                }
            });
            contentloader.onerror.subscribe( function(e) {
                console.log(e);
            });                
            contentloader.load({
                url : content
            }); 
            
        }
    }
    
    return {
        init:function () {
            tactile.foundation.ImageScaler.run();
            registerListener();
            displaySplashScreen();
        }
    }
};


